package com.yjc.drygoods.search.servcie.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjc.common.constant.EsConstant;
import com.yjc.common.to.PurchaseDetailTo;
import com.yjc.common.to.SkuEsModel;
import com.yjc.common.utils.R;
import com.yjc.drygoods.search.config.DryGoodsElasticSearchConfig;
import com.yjc.drygoods.search.feign.ProductFeignService;
import com.yjc.drygoods.search.servcie.MallSearchService;
import com.yjc.drygoods.search.vo.SearchAttrRespVo;
import com.yjc.drygoods.search.vo.SearchParam;
import com.yjc.drygoods.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yjc
 * @create 2022-09-12 17:07
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ProductFeignService productFeignService;


    @Override
    public SearchResult search(SearchParam searchParam) {
        //1.动态构建DSL语句
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        SearchResponse response = null;
        try {
            response = client.search(searchRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //2.封装解析ES返回结果
        SearchResult searchResult = buildSearchResponse(response, searchParam);

        return searchResult;
    }


    /**
     * 封装解析ES返回结果
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResponse(SearchResponse response, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        //1.返回当前所有查询到的商品
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (response.getHits().getHits() != null && response.getHits().getHits().length > 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        searchResult.setProducts(skuEsModels);
//
//        //2.当前所有商品涉及到的所有属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        ArrayList<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            //属性名
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            //属性所有的属性值
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(attrValueBucket -> {
                String attrValue = attrValueBucket.getKeyAsString();
                return attrValue;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);
//        //3.当前所有商品涉及到的所有品牌信息
//        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
//        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
//        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
//            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
//            //品牌id
//            long brandId = bucket.getKeyAsNumber().longValue();
//            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
//            //品牌照片
//            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
//            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
//            //品牌名称
//            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
//            brandVo.setBrandId(brandId);
//            brandVo.setBrandImg(brandImg);
//            brandVo.setBrandName(brandName);
//            brandVos.add(brandVo);
//        }
//        searchResult.setBrands(brandVos);
//        //4.当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //三级分类id
            long catalogId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            //三级分类名称
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);
//
//        //5.分页信息-当前页码
        Integer pageNum = searchParam.getPageNum();
        searchResult.setPageNum(pageNum);
//        //6.分页信息-总记录数
        TotalHits totalHits = response.getHits().getTotalHits();
        searchResult.setTotal(totalHits.value);
//        //7.分页信息-总页码
        Integer totalPages = (int) totalHits.value % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) totalHits.value / EsConstant.PRODUCT_PAGESIZE : (int) totalHits.value / EsConstant.PRODUCT_PAGESIZE + 1;
        searchResult.setTotalPages(totalPages);
        //8.页码条(新增)
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        //9.面包屑导航(新增)
        List<SearchResult.NavVo> collect = new ArrayList<>();
        //属性面包屑
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            collect = searchParam.getAttrs().stream().map(item -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] attr = item.split("_");
                R info = productFeignService.info(Long.parseLong(attr[0]));

                List<Long> attrId = searchResult.getAttrIds();
                attrId.add(Long.parseLong(attr[0]));
                if (info.getCode() == 0) {
                    SearchAttrRespVo attr1 = info.getData("attr", new TypeReference<SearchAttrRespVo>() {
                    });
                    navVo.setNavName(attr1.getAttrName());
                } else {
                    navVo.setNavName(attr[0]);
                }
                navVo.setNavValue(attr[1]);
                //取消链接中该面包屑属性
                String queryString = replaceQueryString(searchParam, item, "attrs");
                navVo.setLink("http://search.drygoods.top/list.html?" + queryString);
                return navVo;
            }).collect(Collectors.toList());
        }
        searchResult.setNavs(collect);
//        //品牌面包屑
//        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
//            List<SearchResult.NavVo> navs = searchResult.getNavs();
//            SearchResult.NavVo navVo = new SearchResult.NavVo();
//            R r = productFeignService.infoBrands(searchParam.getBrandId());
//            if (r.getCode() == 0) {
//                List<BrandVo> brandInfos = r.getData(new TypeReference<List<BrandVo>>() {
//                });
////                brandInfos.forEach(System.out::println);
//                StringBuffer stringBuffer = new StringBuffer();
//                String queryString = "";
//
//                for (BrandVo brandInfo : brandInfos) {
//                    stringBuffer.append(brandInfo.getName() + ";");
//                    queryString = replaceQueryString(searchParam, brandInfo.getBrandId() + "", "brandId");
//                }
//                navVo.setNavName("品牌");
//                navVo.setNavValue(stringBuffer.toString());
//                navVo.setLink("http://search.drygoods.top/list.html?" + queryString);
//            }
//            navs.add(navVo);
//        }

        //分类，不需要加面包屑取消

        return searchResult;

    }

    private String replaceQueryString(SearchParam searchParam, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");//浏览器对空格的编译和java不一致
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return searchParam.getQueryString().replace("&" + key + "=" + encode, "");
    }

    /**
     * 构建干货需求查询条件
     *
     * @param spuId
     * @return
     */
    @Override
    public Double searchPurchaseSpuNum(Long spuId) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 查询指定spuId干货采购需求信息
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.termQuery("spuId", spuId));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.YEAR, -1);
        Date oldMonth = calendar.getTime();
        long oldTime = oldMonth.getTime();
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+1);
        Date newMonth = calendar.getTime();
        long newTime = newMonth.getTime();
        log.info("oldMonth:{},newMonth:{}",oldMonth,newMonth);
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("updateTime").gte(oldTime).lte(newTime));

        sourceBuilder.query(boolQueryBuilder);
        /**
         * 聚合分析出指定spuId干货去年的当今月份的平均进货量
         */
        AvgAggregationBuilder spu_num_agg = AggregationBuilders.avg("spuNum_agg");
        spu_num_agg.field("spuNum");
        sourceBuilder.aggregation(spu_num_agg);
        System.out.println("构建的DSL" + sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PURCHASEDETAIL_INDEX}, sourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if (response.getHits().getHits() != null && response.getHits().getHits().length > 0) {
//            for (SearchHit hit : response.getHits().getHits()) {
//                String sourceAsString = hit.getSourceAsString();
//                PurchaseDetailTo purchaseDetailTo = JSON.parseObject(sourceAsString, PurchaseDetailTo.class);
//                log.info("purchaseDetailTo:{}",purchaseDetailTo);
//            }
//        }
        log.info("response:{}", response);
        ParsedAvg aggregation = response.getAggregations().get("spuNum_agg");
        double value = aggregation.getValue();
        log.info("value:{}", value);
        return value;
    }

    /**
     * 动态构建DSL语句
     *
     * @param searchParam
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 1.模糊匹配，过滤
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1-1.模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        //1-2.过滤-->按照分类
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //1-3.过滤-->按照品牌
//        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
//            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
//        }
        //1-4.过滤-->按照库存
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //1-5.过滤-->按照价格区间
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder skuPriceRange = QueryBuilders.rangeQuery("skuPrice");
            String[] skuPriceSplits = searchParam.getSkuPrice().split("_");
            if (skuPriceSplits.length == 2) {
                skuPriceRange.gte(skuPriceSplits[0]);
                skuPriceRange.lte(skuPriceSplits[1]);
            } else if (skuPriceSplits.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    skuPriceRange.lte(skuPriceSplits[0]);
                } else if (searchParam.getSkuPrice().endsWith("_")) {
                    skuPriceRange.gte(skuPriceSplits[0]);
                }
            }
            boolQueryBuilder.filter(skuPriceRange);
        }
        //1-6.过滤-->按照属性
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder boolQueryBuilderAttr = new BoolQueryBuilder();
                String[] attrAndValue = attr.split("_");
                //过滤属性id
                boolQueryBuilderAttr.must(QueryBuilders.termQuery("attrs.attrId", attrAndValue[0]));
                //过滤属性值
                boolQueryBuilderAttr.must(QueryBuilders.termsQuery("attrs.attrValue", attrAndValue[1].split(":")));

                //添加进一个nested嵌入式过滤
                boolQueryBuilder.filter(QueryBuilders.nestedQuery("attrs", boolQueryBuilderAttr, ScoreMode.None));
            }
        }

        sourceBuilder.query(boolQueryBuilder);


        /**
         * 2.排序，分页，高亮
         */
        //2-1.排序
        String sort = searchParam.getSort();
        if (!StringUtils.isEmpty(sort)) {
            String[] skuPriceSorts = sort.split("_");
            sourceBuilder.sort(skuPriceSorts[0], skuPriceSorts[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }
        //2-2.分页
        Integer pageNum = searchParam.getPageNum();//页码
        sourceBuilder.from((pageNum - 1) * EsConstant.PRODUCT_PAGESIZE);//起始
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2-3.高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        sourceBuilder.highlighter(highlightBuilder.field("skuTitle").preTags("<b style='color:red'>").postTags("</b>"));

        /**
         * 3.聚合分析
         */
        //3-1.品牌聚合
//        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
//        //品牌id
//        brand_agg.field("brandId").size(50);
//        //品牌名称
//        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
//        //品牌图片
//        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
//        //1.聚合brand
//        sourceBuilder.aggregation(brand_agg);

        //3-2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        //分类id
        catalog_agg.field("catalogId").size(50);
        //分类名称
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        //2.聚合catalog
        sourceBuilder.aggregation(catalog_agg);

        //3-3.属性聚合
        //嵌入式对象属性父聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        //属性id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        //属性名称
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        nested.subAggregation(attr_id_agg);
        //3.聚合attrs
        sourceBuilder.aggregation(nested);

        System.out.println("构建的DSL" + sourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
